import { Component,createRef} from 'react';
import { NavBar, ProductCard, Toast, SubmitBar, Checkbox,Stepper } from 'react-vant'
import { Ellipsis, WapHomeO } from '@react-vant/icons'
import './index.less'
import {addOrReduceGoodsNum} from '@/Api/cart'
import {getPreOrderNum} from '@/Api/order';
import WithRouter from '@/router/WithRouter'
import {connect} from 'react-redux'
import {getCartListAction,changeCartGoodsNum} from '../../redux/action/cartAciton'
class Cart extends Component {
    // 创建ref对象用来保存CheckboxGroup组件实例
    CheckboxGroupRef = createRef();
    state = {
        cartList: [],
        checkList:[]
    }
    render() {
        let { checkList} = this.state;
        return (
            <div id='cart'>
                <NavBar
                    title="购物车"
                    leftText={<WapHomeO fontSize={20} color='#fff' />}
                    rightText={<Ellipsis fontSize={20} color='#fff' />}
                    onClickLeft={() => {
                        this.props.router.navigate('/index/home')
                    }}
                    fixed
                />
                <Checkbox.Group value={checkList} onChange={(names)=>this.changeCheck(names)} ref = {this.CheckboxGroupRef}>
                    {
                        this.props.cartReducer.cartList.map((item, index) => {
                            return (
                                <div key={index} className='cartGoods'>
                                    <ProductCard
                                        num={item.cartNum}
                                        price={item.price}
                                        desc={item.suk}
                                        title={item.storeName}
                                        thumb={item.image}
                                        footer={
                                            <div style={{marginTop:"10px"}}>
                                                <Stepper
                                                    value={item.cartNum}
                                                    onChange={(newNum)=>this.changeCartNum(newNum,index)}
                                                    theme='round'
                                                    buttonSize='15'
                                                    disableInput
                                                />
                                            </div>
                                        }
                                    />
                                    <div className='goodsCheckBox'>
                                        <Checkbox name={item} checkedColor='#ee0a24'></Checkbox>
                                    </div>
                                </div>
                            )
                        })
                    }
                </Checkbox.Group>
                <SubmitBar
                    price={this.getCartSumPrice()*100}
                    buttonText="提交订单"
                    onSubmit={()=>this.subMitOrder()}
                >
                    <Checkbox checkedColor='#ee0a24' checked={this.props.cartReducer.cartList.length===checkList.length} onClick={()=>{
                        if(this.props.cartReducer.cartList.length === checkList.length){
                             this.setState({
                                checkList:[]
                             })
                        }else{
                            this.setState({
                                checkList:this.props.cartReducer.cartList
                            })
                        }
                    }}>全选</Checkbox>
                </SubmitBar>
            </div>
        )
    }
    componentDidMount() {
        let cartList = this.props.cartReducer.cartList;
        if(cartList.length ===0){
            this.props.dispatch(getCartListAction())
        }
    }
 
   async changeCartNum(newNum,index){
        let cartList = this.props.cartReducer.cartList;
         // 根据索引获取当前要改变数量得商品对象
        let goods = cartList[index];
        //发送请求更改购物车数量
        let res = await addOrReduceGoodsNum({
            number:newNum,
            id:goods.id
        });
        if(res.data.code !==200){
            Toast(res.data.message);
            return
        }
        Toast.success("操作成功")
        this.props.dispatch(changeCartGoodsNum(index,newNum))
    }
    changeCheck(names){
        console.log(names)
        this.setState({
            checkList:names
        })
    }
    // 计算购物车总价
    getCartSumPrice(){
        // 获取选中得购物车数据
        let {checkList} = this.state;
        let sum = 0;
        checkList.forEach(item=>{
            // 计算单个商品总价 
            let goodsPrice = item.price*item.cartNum;
            sum+=goodsPrice
        })
        return sum
    }
    async subMitOrder(){
        // 获取请求参数
        // 获取所有选中得商品规格id
        let {checkList} = this.state;
        let orderDetails =[]
        checkList.forEach(item=>{
            console.log(item.id)
            orderDetails.push({
                shoppingCartId:item.id
            })
        })
        console.log(orderDetails)
        let res = await getPreOrderNum({orderDetails,preOrderType:"shoppingCart"});
        console.log(res)
        if(res.data.code!==200){
            return
        }
        this.props.router.navigate("/confrimorder", {
            state: {
                preOrderNo: res.data.data.preOrderNo
            }
        });
    }
}
export default connect((state)=>{
    return state
})(WithRouter(Cart));